package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import android.app.Fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.view_type.ListAdapter;
import com.example.myapplication.bean.Person;
import com.example.myapplication.dao.MySQLiteOpenHelper;
import com.example.myapplication.databinding.Activity2MainHomeBinding;
import com.example.myapplication.service.SharedPreferencesService;

import java.util.List;

public class MainActivityHome extends Fragment {

    private Activity2MainHomeBinding homeBinding;
    private Intent intent;
    private View view;
    private List<Person> personList;
    private ListAdapter ListAdapter;
    private MySQLiteOpenHelper mySQLiteOpenHelper;
    // 抽屉导航，开启为true，隐藏为false
    private boolean isDrawerOpen;
    // 查询标识，查询为true，未查询为false
    private boolean isQuery;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        homeBinding = Activity2MainHomeBinding.inflate(inflater, container, false);

        // 保持当前页面布局不被软键盘顶起
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        mySQLiteOpenHelper = new MySQLiteOpenHelper(getContext());
        Integer userId = (Integer) SharedPreferencesService.getUserInfo(getContext()).get("userId");
        personList = mySQLiteOpenHelper.queryPersonByCondition(0, null, null, userId);
        homeBinding = Activity2MainHomeBinding.inflate(getLayoutInflater());

        ListAdapter = new ListAdapter(personList, getContext());
        homeBinding.homeList.setAdapter(ListAdapter);

        homeBinding.homeTop.topReSearch.setVisibility(View.VISIBLE);
        homeBinding.homeTop.topSearch.setVisibility(View.VISIBLE);

        // 列表滑动监听
        homeBinding.homeList.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                if (i > 1) {
                    homeBinding.homeFloatGd.setVisibility(View.VISIBLE);
                } else {
                    homeBinding.homeFloatGd.setVisibility(View.GONE);
                }
            }
        });

        // 返回顶部
        homeBinding.homeFloatGd.setOnClickListener(view -> {
            // 滑动到顶层
            homeBinding.homeList.smoothScrollToPosition(0);
        });

        // 列表点击事件
        homeBinding.homeList.setOnItemClickListener((adapterView, view, i, l) -> {
            Person person = personList.get(i);
            if (getActivity() != null) {
                intent = new Intent(getActivity(), MainActivity2Edit.class);
                intent.putExtra("name", person.getName());
                intent.putExtra("sex", person.getSex());
                intent.putExtra("phone", person.getPhone());
                intent.putExtra("phone2", person.getPhone2());
                intent.putExtra("relation", person.getRelation());
                intent.putExtra("reText", person.getReText());
                intent.putExtra("address", person.getAddress());

                // 修改标识
                intent.putExtra("home", "update");
                getActivity().startActivityIfNeeded(intent, 1);
            }
        });

        // 列表长按事件
        homeBinding.homeList.setOnItemLongClickListener((adapterView, view, i, l) -> {
            Person person = personList.get(i);
            LayoutInflater inflater2 = LayoutInflater.from(getActivity());
            View customView = inflater2.inflate(R.layout.pop_up, null);
            TextView title = customView.findViewById(R.id.up_title);
            TextView message = customView.findViewById(R.id.up_tip);
            title.setText("删除提示");
            message.setText("是否删除 " + person.getName() + "的信息");
            // 创建一个弹窗构造器
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setView(customView);
            // 创建并显示弹窗
            AlertDialog dialog = builder.create();
            dialog.show();
            // 弹窗-确认
            TextView sure = customView.findViewById(R.id.up_confirm);
            sure.setOnClickListener(view1 -> {
                boolean isSuccess = mySQLiteOpenHelper.deletePerson(person);
                if (isSuccess) {
                    Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();
                    showQueryData();
                } else {
                    Toast.makeText(getContext(), "删除失败", Toast.LENGTH_SHORT).show();
                }
                dialog.cancel();
            });
            // 弹窗-取消
            TextView off = customView.findViewById(R.id.up_cancel);
            off.setOnClickListener(view1 -> {
                dialog.cancel();
            });
            return true;
        });

        // 返回
        homeBinding.homeTop.topReturn.setOnClickListener(view -> {
            exitHint();
        });


        // 搜索 -- 打开抽屉
        homeBinding.homeTop.topSearch.setOnClickListener(view -> {
            String name = homeBinding.searchText.getText().toString().trim();
            if (name.isEmpty()) {
                homeBinding.resetBtn.setText("关　闭");
            } else {
                homeBinding.resetBtn.setText("清　空");
            }
            homeBinding.homeDrawer.openDrawer(Gravity.RIGHT);
        });

        // 抽屉监听事件
        homeBinding.homeDrawer.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(@NonNull View drawerView) {
                isDrawerOpen = true;
            }

            @Override
            public void onDrawerClosed(@NonNull View drawerView) {
                isDrawerOpen = false;
                // 关闭系统键盘
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(homeBinding.searchText.getWindowToken(), 0);

                if (!isQuery) {
                    showQueryData();
                    homeBinding.homeTop.topReturn.setVisibility(View.VISIBLE);
                    homeBinding.homeTop.topReset.setVisibility(View.GONE);
                }
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });

        // 搜索--查询
        homeBinding.searchBtn.setOnClickListener(view -> {
            String name = homeBinding.searchText.getText().toString().trim();
            if (!TextUtils.isEmpty(name)) {
                long count = search(name);
                homeBinding.searchTip.setText("共搜索出" + count + "条数据");
                if (count > 0) {
                    isQuery = true;
                    homeBinding.searchTip.setTextColor(ContextCompat.getColor(getActivity(), R.color.yellow));
                    homeBinding.homeTop.topReturn.setVisibility(View.GONE);
                    homeBinding.homeTop.topReset.setVisibility(View.VISIBLE);
                    homeBinding.homeDrawer.closeDrawers();
                    homeBinding.searchText.clearFocus();
                    // 关闭系统键盘
                    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(homeBinding.searchText.getWindowToken(), 0);
                } else {
                    isQuery = false;
                    homeBinding.searchTip.setTextColor(ContextCompat.getColor(getContext(), R.color.red));
                }
                homeBinding.homeList.setAdapter(new ListAdapter(personList, getContext()));
            }
            homeBinding.resetBtn.setText("关　闭");
        });

        // 刷新搜索
        homeBinding.homeTop.topReSearch.setOnClickListener(view -> {
            if (isQuery) {
                Toast.makeText(getContext(), "刷新成功，共" +
                        search(homeBinding.searchText.getText().toString().trim()) + "条数据", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getContext(), "刷新成功，共" +
                        showQueryData() + "条数据", Toast.LENGTH_SHORT).show();
            }
        });

        // 取消搜索
        homeBinding.homeTop.topReset.setOnClickListener(view -> {
            homeBinding.homeTop.topReturn.setVisibility(View.VISIBLE);
            isQuery = false;
            homeBinding.searchText.setText("");
            homeBinding.searchTip.setText("");
            showQueryData();
            homeBinding.homeTop.topReset.setVisibility(View.GONE);
        });

        // 无字/有字有查-关闭，有字无查-清空
        homeBinding.resetBtn.setOnClickListener(view -> {
            switch (homeBinding.resetBtn.getText().toString().trim().substring(0, 1)) {
                case "关":
                    if (!isQuery) {
                        personList = mySQLiteOpenHelper.queryPersonByCondition(0, null, null, userId);
                        homeBinding.homeList.setAdapter(new ListAdapter(personList, getContext()));
                    }
                    homeBinding.homeDrawer.closeDrawer(GravityCompat.END);
                    break;
                case "清":
                    homeBinding.searchText.setText("");
                    homeBinding.searchTip.setText("");
                    isQuery = false;
                    homeBinding.resetBtn.setText("关　闭");
                    break;
                default:
            }
        });

        // 搜索框监听事件
        homeBinding.searchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!homeBinding.searchText.getText().toString().trim().isEmpty()) {
                    Integer userId = (Integer) SharedPreferencesService.getUserInfo(getContext()).get("userId");
                    int count = mySQLiteOpenHelper.queryCount(homeBinding.searchText.getText().toString().trim(), userId);
                    homeBinding.searchTip.setTextColor(ContextCompat.getColor(getContext(), R.color.yellow));
                    if (count > 0) {
                        homeBinding.searchTip.setText("已为您搜索出" + count + "条数据");
                    } else {
                        homeBinding.searchTip.setText("未能查到数据");
                    }
                    homeBinding.resetBtn.setText("清　空");
                } else {
                    homeBinding.searchTip.setText("");
                    homeBinding.resetBtn.setText("关　闭");
                }
            }
        });


        return homeBinding.getRoot();
    }

    // 退出APP提示
    protected void exitHint() {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View customView = inflater.inflate(R.layout.pop_up, null);
        TextView title = customView.findViewById(R.id.up_title);
        TextView message = customView.findViewById(R.id.up_tip);
        title.setText("关闭通讯录提示");
        message.setText("确认要退出通讯录吗？");
        // 创建一个弹窗构造器
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(customView);
        // 创建并显示弹窗
        AlertDialog dialog = builder.create();
        dialog.show();
        // 弹窗-确认
        TextView sure = customView.findViewById(R.id.up_confirm);
        sure.setOnClickListener(view1 -> {
            SharedPreferencesService.deleteUserInfo(getContext());
            getActivity().finish();
        });
        // 弹窗-取消
        TextView off = customView.findViewById(R.id.up_cancel);
        off.setOnClickListener(view1 -> {
            dialog.cancel();
        });
    }

    // 搜索处理
    @SuppressLint("SetTextI18n")
    private long search(String name) {
        Integer userId = (Integer) SharedPreferencesService.getUserInfo(getContext()).get("userId");
        personList = mySQLiteOpenHelper.queryPersonByCondition(1, name, null, userId);
        return personList.size();
    }

    // 渲染列表
    private long showQueryData() {
        if (personList != null) {
            personList.clear();
        }
        Integer userId = (Integer) SharedPreferencesService.getUserInfo(getContext()).get("userId");
        personList = mySQLiteOpenHelper.queryPersonByCondition(0, null, null, userId);
        ListAdapter = new ListAdapter(personList, getContext());
        homeBinding.homeList.setAdapter(ListAdapter);
        return personList.size();
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }




    /*public void Load() {
        //title.setText("当前时间：\n" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

    }*/

    /*在全局区域抽屉监听触摸事件*/
    /*@Override
    public boolean onTouchEvent(MotionEvent event) {
        if (isDrawerOpen && drawerLayout.onTouchEvent(event)) {
            isDrawerOpen = false;
        }
        return super.onTouchEvent(event);
    }*/
}